<template>
  <div class="container">
    <el-card class="box-card" v-loading="isLoading">
      <div class="box">
        <el-form :inline="true" class="demo-form-inline" ref="form" :model="form">
          <el-form-item label="目录名称">
            <el-input v-model="form.directoryName"></el-input>
          </el-form-item>

          <el-form-item class="box1" label="状态">
            <el-select v-model="form.state" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button size="small" @click="resetForm">清除</el-button>
            <el-button type="primary" size="small" @click="onSubmit">搜索</el-button>
          </el-form-item>
        </el-form>

        <div>
          <el-button
            size="small"
            type="text"
            icon="el-icon-back"
            @click="buttonclick"
            v-if="routeValue !== ''"
            >返回学科</el-button
          >
          <el-button type="success" icon="el-icon-edit" size="small" @click="addDirectory"
            >新增目录</el-button
          >
        </div>
      </div>

      <template>
        <el-alert :title="titles" type="info" show-icon :closable="false"> </el-alert>
        <el-table
          class="box2"
          :data="tableData"
          style="width: 100%"
          :header-cell-style="{ background: '#FAFAFA', color: '#909399' }"
        >
          <el-table-column type="index" :index="indexMethod" prop="id" label="序号" min-width="40">
          </el-table-column>
          <el-table-column prop="subjectName" label="所属学科"> </el-table-column>
          <el-table-column prop="directoryName" label="目录名称"> </el-table-column>
          <el-table-column prop="username" label="创建者"> </el-table-column>
          <el-table-column prop="addDate" label="创建日期">
            <template #default="{ row }">
              {{ formateTimeFn(row.addDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="totals" label="面试题数量"> </el-table-column>
          <el-table-column prop="state" label="状态" :formatter="formateFn">
            <template #default="{row}">
              {{ row.state ? '启用' : '禁用' }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作">
            <template #default="{row}">
              <el-button type="text" @click="submitState(row)">
                {{ row.state ? '禁用' : '启用' }}
              </el-button>
              <el-button type="text" :disabled="Boolean(row.state)" @click="modifyList(row)"
                >修改</el-button
              >
              <el-button type="text" :disabled="Boolean(row.state)" @click="deleList(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 分页组件 -->
      <!--
  属性:
    1. current-page 标记当前页 (谁高亮)
    2. page-sizes 可供选择的每页条数列表
    3. page-size 起作用的每页条数
    4. layout 布局, 控制是展示的控件列表布局
    5. total 总条数
  方法:
    @size-change="handleSizeChange" 每页条数变化
    @current-change="handleCurrentChange" 当前页变化
-->
      <el-pagination
        style="margin-top: 10px"
        background
        layout="->,total, sizes, prev,  pager, next, jumper"
        :current-page="form.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="form.pagesize"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 新增编辑的弹层 -->
    <el-dialog
      :visible="showDialog"
      :title="showTitle"
      @close="hideDirectory"
      width="30%"
      :close-on-click-modal="false"
    >
      <!-- 表单内容 -->
      <el-form label-width="100px" :model="formDate" :rules="rules" ref="addForm">
        <el-form-item label="所属学科" prop="subjectID">
          <el-select placeholder="请选择" v-model="formDate.subjectID">
            <el-option
              v-for="item in subjectNameList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input class="kuan" v-model="formDate.directoryName"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <div style="text-align: right">
          <el-button @click="hideDirectory">取消</el-button>
          <el-button type="primary" @click="confirAddsubject">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { list, add, changeState, remove, update, detail } from '@/api/hmmm/directorys.js'
import { simple } from '@/api/hmmm/subjects.js'
import { status } from '@/api/hmmm/constants.js'
import dayjs from 'dayjs'
export default {
  name: 'Directorys',
  data () {
    return {
      titles: '',
      tableData: [],
      isLoading: false,
      total: 0,
      options: status,
      showDialog: false,
      form: {
        page: 1, // 当前页
        pagesize: 10, // 每页条数
        pages: '',
        state: null,
        directoryName: '',
        subjectName: null,
        subjectID: ''
      },
      formDate: {
        directoryName: '',
        subjectID: ''
      },
      rules: {
        directoryName: [{ required: true, message: '请输入目录名称', trigger: 'blur' }],
        subjectID: [{ required: true, message: '请输入目录名称', trigger: 'blur' }]
      },
      subjectNameList: [],
      hidden: false,
      routeValue: '',
      showTitle: '',
      id: '',
      data: {}
    }
  },
  created () {
    this.getrols() // 获取角色列表
    this.subjectList() // 获取学科列表
    this.data = this.$route.query
  },
  mounted () {
    this.routeValue = this.$route.query.name || ''
    if (this.$route.query.id) {
      this.getrols()
    }
  },
  /**
   * 获取列表
   */
  methods: {
    async getrols () {
      this.form.subjectID = this.data.id
      // this.isLoading = true
      const { data } = await list({ page: this.form.page, pagesize: this.form.pagesize, subjectID: this.form.subjectID })
      // console.log(data)
      const { counts, items } = data
      this.total = counts
      this.tableData = items
      this.titles = `数据一共${this.total}条`
      // this.isLoading = false
    },
    handleSizeChange (val) {
      this.form.pagesize = val
      this.form.page = 1
      this.getrols()
    },
    handleCurrentChange (val) {
      this.form.page = val
      this.getrols()
    },
    indexMethod (index) {
      return (this.form.page - 1) * this.form.pagesize + index + 1
    },
    /**
     * 枚举状态
     */

    formateFn (row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      // return Number(cellValue) === 1 ? '启用' : '禁用'
      const obj = status.find(item => item.value === Number(cellValue))
      return obj ? obj.label : '未知'
    },
    /**
     * 处理时间格式
     */
    formateTimeFn (time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    },
    /**
     * 打开添加弹窗
     */
    addDirectory () {
      this.showDialog = true
      this.showTitle = '新增目录'
    },
    /**
     * 关闭弹窗
     */
    hideDirectory () {
      this.showDialog = false
      this.$refs.addForm.resetFields()
    },
    /**
     * 打开确定按钮
     */
    confirAddsubject () {
      this.$refs.addForm.validate(async flag => {
        if (!flag) {
          return
        }
        if (this.id) {
          await update(this.formDate)
          // 消息提示
          this.$message.success('修改成功')
          // this.clearFormdate()
        } else {
          // 接口提交
          await add(this.formDate)
          // 消息提示
          this.$message.success('操作成功')
        }
        // 关闭弹窗
        this.hideDirectory()
        // 重新渲染
        this.getrols()
        this.clearFormdate()
      })
    },
    clearFormdate () {
      this.$refs.addForm.resetFields()
      this.formDate = {
        directoryName: '',
        subjectID: ''
      }
    },
    /**
     * 获取学科列表
     */
    async subjectList () {
      const res = await simple()
      // console.log(res)
      this.subjectNameList = res.data
    },
    /**
     * 清除
     */
    resetForm () {
      this.$refs.form.resetFields()
      this.form = {
        page: 1, // 当前页
        pagesize: 10, // 每页条数
        pages: '',
        state: null,
        directoryName: '',
        subjectName: null
      }
      this.getrols()
    },
    /**
     * 搜索
     */
    async onSubmit () {
      // this.getrols()
      const { data } = await list({ directoryName: this.form.directoryName })
      // console.log(res)
      this.form.page = data.page
      this.total = data.counts
      this.titles = `数据一共${this.total}条`
      this.tableData = data.items
      this.titles = `数据一共${this.total}条`
    },
    /**
     * 启用禁用
     */
    async submitState (data) {
      // console.log(data)
      data.state = data.state ? 0 : 1
      await changeState(data)
      this.$message.success('操作成功')
    },
    /**
     * 跳转
     */
    buttonclick () {
      this.$router.push('/subjects/list')
    },
    /**
     * 删除
     */
    deleList (row) {
      // console.log(row)
      this.$confirm('此操作将永久删除该目录, 是否继续?', '提示', {
        type: 'warning'
      })
        .then(async () => {
          await remove(row)
          this.$message.success('删除成功')
          if (this.tableData.length === 1 && this.form.page > 1) {
            this.form.page--
          }
          this.getrols()
        })
        .catch(() => {})
    },
    /**
     * 修改
     */
    async modifyList (row) {
      const { data } = await detail(row)
      this.id = data.id
      // console.log(res)
      this.addDirectory()
      this.formDate = data
      this.showTitle = '修改目录'
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  padding: 0 10px;
  margin: 10px 0;
}
.box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.box1 {
  margin-left: 30px;
}
.box2 {
  margin-top: 10px;
}
.demo-form-inline {
  margin-left: 10px;
}
.kuan {
  width: 225px;
}
</style>
